const bucket = 'nexhome-home-page';

const qiniu = require('qiniu');
const config = require('../config/config');

const qiniuConfig = new qiniu.conf.Config();
// 空间对应的机房
qiniuConfig.zone = qiniu.zone.Zone_z2;

module.exports = {

  getUploadToken() {
    const mac = new qiniu.auth.digest.Mac(config.qiniu.accessKey, config.qiniu.secretKey);
    const options = {
      // scope: `${bucket}:${fileName}`,
      scope: bucket,
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    return putPolicy.uploadToken(mac);
  },

  uploadFile(fileName, filePath, callback) {
    const saveFileName = `${Date.now()}_${fileName}`;
    const formUploader = new qiniu.form_up.FormUploader(config);
    const uploadToken = this.getUploadToken(saveFileName);
    const putExtra = new qiniu.form_up.PutExtra();

    formUploader.putFile(uploadToken, saveFileName, filePath, putExtra, callback);
  },
};
